import { useHttp } from '@src/utils/http';
import { QueryKey, useMutation, useQuery } from 'react-query';
import { useAddConfig, useDeleteConfig, useEditConfig } from '@src/utils/use-optimistic-options';
import { Project } from '@src/types/project';
import { cleanObject } from '@src/utils/index';

/**
 * =========================  查询项目  ==========================
 * @param param
 */
export const useProjects = (param?: Partial<Project>) => {
  const client = useHttp();

  return useQuery<Project[]>(['projects', cleanObject(param)], () => client('projects', { data: param }));
};

/**
 * =========================  修改项目 ==========================
 */
export const useEditProject = (queryKey: QueryKey) => {
  const client = useHttp();
  return useMutation(
    (params: Partial<Project>) =>
      client(`projects/${params.id}`, {
        method: 'PATCH',
        data: params,
      }),
    useEditConfig(queryKey)
  );
};

/**
 * =========================  添加 ==========================
 * @param queryKey
 */
export const useAddProject = (queryKey: QueryKey) => {
  const client = useHttp();

  return useMutation(
    (params: Partial<Project>) =>
      client(`projects`, {
        data: params,
        method: 'POST',
      }),
    useAddConfig(queryKey)
  );
};

/**
 * =========================  删除 ==========================
 * @param queryKey
 */
export const useDeleteProject = (queryKey: QueryKey) => {
  const client = useHttp();

  return useMutation(
    ({ id }: { id: number }) =>
      client(`projects/${id}`, {
        method: 'DELETE',
      }),
    useDeleteConfig(queryKey)
  );
};

/**
 * =========================  根据id 查找project ==========================
 * @param id
 */
export const useProject = (id?: number) => {
  const client = useHttp();
  return useQuery<Project>(['project', { id }], () => client(`projects/${id}`), {
    enabled: Boolean(id),
  });
};
